module Controllers.AddSubmission(handleAddSubmission) where

import State.Database
import State.TuuraQueries(AddSubmission(..), NoSuchProblem(..))

import Happstack.State (update)
import Happstack.Server (toResponse,seeOther,ServerPart,Response,ok)
import Controllers.Digestive
import Pages.AddSubmissionDigestive
import Text.Blaze(ToHtml(..))

-- | HTTP handler for the "Add a new submission" page
handleAddSubmission :: String -- ^ The URL to return to after the form has been submitted
                     -> ServerPart Response -- ^ The Add problem form HTTP handler
handleAddSubmission returnUrl = runForm (handleSubmit returnUrl) (submissionForm (const (return True)))
    -- runSimpleForm "addSubmission" submissionForm (handleSubmit returnUrl)

-- | Handles the successful form submission
handleSubmit :: String -- ^ The URL to return to
             -> (ProblemId, Program) -- ^ The submitted information
             -> ServerPart Response -- The HTTP response
handleSubmit returnUrl submission = do
    updateResult <- update (AddSubmission submission)
    case updateResult of
        Left (NoSuchProblem problem) -> ok $ toResponse $ toHtml $ "no such problem: " ++ show problem
        Right (SubmissionId _submission) -> seeOther returnUrl (toResponse())
